window.onload = function() {
    document.getElementById("loginForm").onsubmit = function(event) {
        event.preventDefault()
        submitForm(event.target.id)
    }

    document.getElementById("registerForm").onsubmit = function(event) {
        event.preventDefault()
        submitForm(event.target.id)
    }

    function submitForm(formId) {
        var xhr = new XMLHttpRequest()
        var formData = new FormData(document.getElementById(formId))
        xhr.open("POST", "/" + formId.replace('Form',''), true)
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var response = JSON.parse(xhr.responseText)
                var messageContainer = document.getElementById("messageContainer")
                var messageIframe = document.getElementById("messageIframe")
                messageContainer.style.display = "block"

                if (response.status === "error") {
                    if (formId === "loginForm") {
                        document.getElementById("username").value = ""
                        document.getElementById("password").value = ""
                        messageIframe.contentDocument.body.innerHTML = response.message
                        setTimeout(function() {
                            messageContainer.style.display = "none"
                        }, 3000)
                    }
                } else if (response.status === 'success') {
                    if (formId === "loginForm") {
                        messageIframe.contentDocument.body.innerHTML = response.message
                        setTimeout(function() {
                            window.location.href = "/home"
                            messageContainer.style.display = "none"
                        }, 1000)
                    } else if (formId === "registerForm") {
                        messageIframe.contentDocument.body.innerHTML = response.message
                        setTimeout(function() {
                            window.location.href = "/login"
                            messageContainer.style.display = "none"
                        }, 1000)
                    }
                }
            }
        };
        xhr.send(formData)
    }

    function toggleForm() {
        var loginForm = document.getElementById("loginForm")
        var registerForm = document.getElementById("registerForm")
        var formTitle = document.getElementById("formTitle")

        if (loginForm.style.display === "none") {
            loginForm.style.display = "block"
            registerForm.style.display = "none"
            formTitle.innerHTML = "登录";
        } else {
            loginForm.style.display = "none";
            registerForm.style.display = "block"
            formTitle.innerHTML = "注册";
        }
    }

    document.querySelector("a[href='javascript:void(0);']").onclick = toggleForm
}
